package org.buptsse.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.crypto.NullCipher;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.buptsse.entity.HistoryItem;
import org.buptsse.entity.TradeDetail;
import org.buptsse.thread.SendMessageThread;
import org.buptsse.ui.R.id;
import org.buptsse.utils.APPConstant;
import org.buptsse.utils.ConnectionChecker;
import org.buptsse.utils.GloableInstance;
import org.buptsse.utils.HttpHelper;
import org.buptsse.utils.ImageService;
import org.buptsse.utils.JsonUtils;

import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

//here i am
public class OneTradeActivity extends Activity {

	
	private String dealid,role;
	private TextView dealidTV,buyerTV,sellerTV,begintimeTV,endtimeTV,dealpriceTV,
					stepTV,booknameTV,pageTV,newpriceTV,authorTV,publisherTV,
					publishtimeTV,descriptionTV,othernameTV,degreeTV,coinTV,
					schoolTV,secondsubjectTV,registtimeTV,othermailTV,otherphoneTV;
	private ImageView otherphotoIV;
	private Button backBT,rejectBT,confirmBT,callBT,smsBT,msgBT;
	private ProgressDialog pDialog;
	private TradeDetail tradeItem;
	
	private Handler handler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			DismissProgreeDialog();
			switch (msg.what) {
			case APPConstant.NetUnavailable:
				Toast.makeText(getApplicationContext(), "网络连接不可用", 1000).show();
				break;
			case APPConstant.getDealDetailError:
				Toast.makeText(getApplicationContext(), "没有相关数据", 1000).show();
				finish();
				break;
			case APPConstant.getDealDetailFinish:
				tradeItem=(TradeDetail) msg.obj;
				FillInfo(tradeItem);
				break;
			case APPConstant.sendMessageError:
				//发送消息成功
				Toast.makeText(getApplicationContext(), "发送失败", 1000).show();
				break;
			case APPConstant.sendMessageFinish:
				//发送消息失败
				Toast.makeText(getApplicationContext(), "发送成功", 1000).show();
				break;
			case APPConstant.acceptDealError:
				//接受订单失败
				Toast.makeText(getApplicationContext(), "操作失败，请稍后再试", 1000).show();
				break;
			case APPConstant.acceptDealFinish:
				//接受订单成功
				tradeItem.setStep("成交");
				stepTV.setText("成交");
				otherphoneTV.setText(tradeItem.getOtherphone());
				othermailTV.setText(tradeItem.getOthermail());
				Toast.makeText(getApplicationContext(), "操作成功", 1000).show();
				break;
			case APPConstant.refuseDealError:
				//拒绝订单失败
				Toast.makeText(getApplicationContext(), "操作失败，请稍后再试", 1000).show();
				break;
			case APPConstant.refuseDealFinish:
				//拒绝订单成功
				stepTV.setText("被卖家拒绝");
				tradeItem.setStep("被卖家拒绝");
				Toast.makeText(getApplicationContext(), "操作成功", 1000).show();
				break;
			}
		}
		
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.l_one_trade);		
		
		//实例化控件
		dealidTV=(TextView) findViewById(R.id.dealid);
		secondsubjectTV=(TextView) findViewById(R.id.secondsubject);
		registtimeTV=(TextView) findViewById(R.id.registtime);
		otherphotoIV=(ImageView) findViewById(R.id.otherphoto);
		othermailTV=(TextView) findViewById(R.id.othermail);
		schoolTV=(TextView) findViewById(R.id.school);
		coinTV=(TextView) findViewById(R.id.coin);
		degreeTV=(TextView) findViewById(R.id.degree);
		othernameTV=(TextView) findViewById(R.id.othername);
		descriptionTV=(TextView) findViewById(R.id.description);
		publisherTV=(TextView) findViewById(R.id.publisher);
		publishtimeTV=(TextView) findViewById(R.id.publishtime);
		authorTV=(TextView) findViewById(R.id.author);
		newpriceTV=(TextView) findViewById(R.id.newprice);
		pageTV=(TextView) findViewById(R.id.page);
		buyerTV=(TextView) findViewById(R.id.buyer);
		sellerTV=(TextView) findViewById(R.id.seller);
		begintimeTV=(TextView) findViewById(R.id.begintime);
		endtimeTV=(TextView) findViewById(R.id.endtime);
		dealpriceTV=(TextView) findViewById(R.id.dealprice);
		stepTV=(TextView) findViewById(R.id.step);
		booknameTV=(TextView) findViewById(R.id.bookname);
		otherphoneTV=(TextView) findViewById(R.id.otherphone);
		
		callBT=(Button) findViewById(R.id.callbutton);
		smsBT=(Button) findViewById(R.id.smsbutton);
		msgBT=(Button) findViewById(R.id.msgbutton);
		rejectBT=(Button) findViewById(R.id.rejectbutton);
		confirmBT=(Button) findViewById(R.id.confirmbutton);
		backBT=(Button) findViewById(R.id.bt_back);
		backBT.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		//拒绝订单
		rejectBT.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(tradeItem==null || tradeItem.getStep().equals("成交") || tradeItem.getStep().equals("被卖家拒绝"))
				{	
					Toast.makeText(getApplicationContext(), "订单已完成", 1000).show();
					return;				
				}
				DealOperationThread dot=new DealOperationThread(getApplicationContext(), dealid, "refuse", null);
				dot.start();
				ShowWaittingDialog("正在操作，请稍等");
			}
		});
		//接收订单
		confirmBT.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(tradeItem==null || tradeItem.getStep().equals("成交") || tradeItem.getStep().equals("被卖家拒绝"))
				{	
					Toast.makeText(getApplicationContext(), "订单已完成", 1000).show();
					return;				
				}
				DealOperationThread dot=new DealOperationThread(getApplicationContext(), dealid, "accept", null);
				dot.start();
				ShowWaittingDialog("正在操作，请稍等");
			}
		});
		
		//打电话
		callBT.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(tradeItem==null || !tradeItem.getStep().equals("成交"))
				{
					Toast.makeText(getApplicationContext(), "为保护双方隐私，只有在成交后才可以给对方打电话哦", 1000).show();
					return;
				}
				Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+ tradeItem.getOtherphone()));
				startActivity(intent);
			}
		});
		
		//发短信
		smsBT.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(tradeItem==null || !tradeItem.getStep().equals("成交"))
				{
					Toast.makeText(getApplicationContext(), "为保护双方隐私，只有在成交后才可以给对方发短信哦", 1000).show();
					return;
				}
				SendSMSDialog();
			}
		});
		
		//发站内信
		msgBT.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(tradeItem==null)
					return;
				ShowMessageDialog("");
			}
		});
		//dealid
		dealid=getIntent().getExtras().getString("dealid");
		role=getIntent().getExtras().getString("role");
		
		//get deal detail
		ShowWaittingDialog("正在加载信息");
		GetDealDetailThread gt=new GetDealDetailThread(this, dealid, role);
		gt.start();
	}

	public void FillInfo(TradeDetail item)
	{
		if(item==null)
			return;
		dealidTV.setText(item.getDealid());
		buyerTV.setText(item.getBuyer());
		sellerTV.setText(item.getSeller());
		begintimeTV.setText(item.getBegintime());
		endtimeTV.setText(item.getEndtime());
		dealpriceTV.setText(item.getDealprice());
		stepTV.setText(item.getStep());
		booknameTV.setText(item.getBookname());
		pageTV.setText(item.getPage());
		newpriceTV.setText(item.getNewprice());
		authorTV.setText(item.getAuthor());
		publisherTV.setText(item.getPublisher());
		publishtimeTV.setText(item.getPublishtime());
		descriptionTV.setText(item.getDescription());
		othernameTV.setText(item.getOthername());
		degreeTV.setText(item.getDegree());
		coinTV.setText(item.getCoin());
		schoolTV.setText(item.getSchool());
		secondsubjectTV.setText(item.getSecondsubject());
		registtimeTV.setText(item.getRegisttime());
		//otherphoneTV.setText(item.getOtherphone());
		//othermailTV.setText(item.getOthermail());
		otherphotoIV.setImageBitmap(ImageService.getImageByUrl(item.getOtherphoto()));
		if(!item.getStep().equals("成交"))
		{
			othermailTV.setText("*******");
			otherphoneTV.setText("******");
		}else {
			otherphoneTV.setText(item.getOtherphone());
			othermailTV.setText(item.getOthermail());
		}
	}
	
	public void ShowMessageDialog(String msg)
	{
		final EditText et=new EditText(this);
		et.setText(msg);
		new AlertDialog.Builder(this).setTitle("请输入您要发送的消息").setIcon(
			     android.R.drawable.ic_dialog_info).setView(
			     et).setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if(et.getText().toString().equals(""))
						{
							Toast.makeText(getApplicationContext(), "消息内容不能为空", 1000).show();
							return;
						}
						SendMessageThread smt=new SendMessageThread(getApplicationContext(),handler,et.getText().toString(),GloableInstance.user.getName(),tradeItem.getOthername(),"false");
						smt.start();
						ShowWaittingDialog("正在发送");
					}
				})
			     .setNegativeButton("取消", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
						}
					}).show();
	}
	
	//发送短息的对话框
	public void SendSMSDialog()
	{
		final EditText et=new EditText(this);
		et.setHint("在这里输入短信内容");
		new AlertDialog.Builder(this).setTitle("输入您要发送的消息").setIcon(
			     android.R.drawable.ic_dialog_info).setView(
			     et).setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if(et.getText().toString().equals(""))
						{
							Toast.makeText(getApplicationContext(), "消息内容不能为空", 1000).show();
							return;
						}
						SmsManager manage=SmsManager.getDefault();  //取得默认的SmsManager用于短信的发送  
	                    List<String> all=manage.divideMessage(et.getText().toString());  //短信的内容是有限的，要根据短信长度截取。逐条发送  
	                    Iterator<String> it=all.iterator();  
	                    while(it.hasNext()){  
	                        manage.sendTextMessage(tradeItem.getOtherphone(), null, it.next(), null, null);  //逐条发送短息  
	                          
	                    }  
					}
				})
			     .setNegativeButton("取消", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
						}
					}).show();
	}
	
	public void ShowWaittingDialog(String msg)
	{
		pDialog=new ProgressDialog(this);
		pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pDialog.setMessage(msg); 
        pDialog.show(); 
	}
	
	public void DismissProgreeDialog()
	{
		if(pDialog!=null)
			pDialog.dismiss();
	}
	
	private class GetDealDetailThread extends Thread
	{
		private Context context;
		private String dealid,role;
		
		public GetDealDetailThread(Context context,String dealid,String role)
		{
			this.context=context;
			this.dealid=dealid;
			this.role=role.equals("买家")?"buyer":"seller";
		}
		
		public void run()
		{
			if(ConnectionChecker.CheckConnection(context, handler)==false)
			{
				return;
			}
			ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("dealid", dealid));
			param.add(new BasicNameValuePair("role", role));
			try {
				String json=HttpHelper.sendPost(APPConstant.getDealDetailUrl, param);
				System.out.println("dealid:"+dealid+" role:"+role);
				System.out.println("get deal detail, json:"+json);
				if(json.contains("failure"))
				{
					//失败
					Message msg=handler.obtainMessage(APPConstant.getDealDetailError);
					handler.sendMessage(msg);
					return;
				}else{
					//成功
					@SuppressWarnings("unchecked")
					LinkedList<TradeDetail> list=(LinkedList<TradeDetail>) JsonUtils.getJsonObject(json, new TypeToken<LinkedList<TradeDetail>>(){}.getType());
					if(list!=null && list.size()>0)
					{
						Message msg=handler.obtainMessage(APPConstant.getDealDetailFinish);
						msg.obj=list.get(0);
						handler.sendMessage(msg);
						return;						
					}else
					{
						Message msg=handler.obtainMessage(APPConstant.getDealDetailError);
						handler.sendMessage(msg);
						return;
					}
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private class DealOperationThread extends Thread
	{
		private Context context;
		private String dealid,action,message;
		
		public DealOperationThread(Context context,String dealid,String action, String message)
		{
			this.context=context;
			this.dealid=dealid;
			this.action=action;
			this.message=message;
		}
		
		public void run()
		{
			if(ConnectionChecker.CheckConnection(context, handler)==false)
			{
				return;
			}
			ArrayList<NameValuePair> param=new ArrayList<NameValuePair>();
			param.add(new BasicNameValuePair("dealid", dealid));
			param.add(new BasicNameValuePair("action", action));
			if(message!=null)
				param.add(new BasicNameValuePair("message", message));
			try {
				String result=HttpHelper.sendPost(APPConstant.dealOperationUrl, param);
				//Log.v("deal id:", dealid);
				//Log.v("action", action);
				//Log.v("deal operation result is:",result);
				if(result.contains("success"))
				{
					//成功
					Message msg=null;
					if(action.equals("accept"))
						msg=handler.obtainMessage(APPConstant.acceptDealFinish);
					else 
						msg=handler.obtainMessage(APPConstant.refuseDealFinish);
					handler.sendMessage(msg);
					return;
				}else {
					//失败
					Message msg=null;
					if(action.equals("accept"))
						msg=handler.obtainMessage(APPConstant.acceptDealError);
					else 
						msg=handler.obtainMessage(APPConstant.refuseDealError);
					handler.sendMessage(msg);
					return;
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
